JS-[forEach篇]-遍歷陣列:for of 與 .forEach()


使用基本for ... of

把for...of做跟.forEach()一樣的事

Arr.entries() 與 Object.entries()

  • arr.entries() 迭代對象是陣列數組時會回傳[index, element]

          const a = ["a", "b", "c"];
    
          for (const [index, element] of a.entries()) {
            console.log(index, element);
          }
    
          // 0 'a'
          // 1 'b'
          // 2 'c'
    
  • Object.entries() 迭代對象是物件時會回傳[key, value]

          const object1 = {
            a: 'somestring',
            b: 42,
          };
    
          for (const [key, value] of Object.entries(object1)) {
            console.log(`${key}: ${value}`);
          }
    
          // Expected output:
          // "a: somestring"
          // "b: 42"
    

.forEach((cur, index,arr) => {...})


.forEach()會調用callback fn,這個callback fn的參數是有順序性的,先後順序是,(當前元素,索引值,陣列本身)

  • .forEach() 總是會返回 undefined,而且不能繼續鏈式调用。其典型的用法是在鏈式调用的末尾执行某些操作
  • 因為返回undefined所以不能使用return關鍵字
  • .forEach()語句不會接受中斷,一旦跑就會loop到元素結束為止

補充:Object.values() 與Object.keys()

  • Object.keys() 會把物件的keys拉出來,成陣列數組元素
    const object1 = {
      a: 'somestring',
      b: 42,
      c: false,
    };

    console.log(Object.keys(object1));
    // Expected output: Array ["a", "b", "c"]
  • Object.values() 會把物件的values拉出來,成陣列數組元素
    const object1 = {
      a: 'somestring',
      b: 42,
      c: false,
    };

    console.log(Object.values(object1));
    // Expected output: Array ["somestring", 42, false]
#for...of #.forEach() #Array.entries() #Object.entries() #Object.keys() #Object.values()







你可能感興趣的文章

Day 140

Day 140

git clone 了一個 Laravel 專案,然後咧?

git clone 了一個 Laravel 專案,然後咧?

Python Table Manners - 管理繁瑣任務

Python Table Manners - 管理繁瑣任務






留言討論